package com.ziyear.rocketmq.controller;

import com.alibaba.fastjson.JSON;
import com.ziyear.rocketmq.enums.BizTypeEnum;
import com.ziyear.rocketmq.enums.MQTypeEnum;
import com.ziyear.rocketmq.enums.OrderOperateEnum;
import com.ziyear.rocketmq.mq.RocketProducerFactory;
import com.ziyear.rocketmq.mq.dto.SendObjectDTO;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 功能描述 : TODO
 *
 * @author Ziyear 2021-03-30 23:08
 */
@RestController
@RequestMapping("/api/rocketmq")
public class DemoController {

    @GetMapping("/praise")
    public Object praise(@RequestParam("userId") Integer userId,
        @RequestParam("liveName") String liveName) {
        Map<String, Object> recordDTO = new HashMap<>(4);
        recordDTO.put("userId", userId);
        recordDTO.put("liveName", liveName);
        SendObjectDTO sendData = new SendObjectDTO();
        sendData.setBody(JSON.toJSONString(recordDTO));
        RocketProducerFactory.getProduct(MQTypeEnum.PRAISE).send(sendData);
        return "success";
    }

    @PostMapping("/register")
    public Object register(Integer userId) {
        SendObjectDTO sendData = new SendObjectDTO();
        sendData.setBizId(userId);
        sendData.setBizType(BizTypeEnum.COUPONS_FOR_NEWCOMERS.getCode());
        RocketProducerFactory.getProduct(MQTypeEnum.DEFAULT).send(sendData);
        return "success";
    }

    @PostMapping("/createOrder")
    public Object createOrder(Integer orderId) {
        SendObjectDTO sendData = new SendObjectDTO();
        sendData.setBizType(BizTypeEnum.ORDER_PAYMENT_TIMEOUT.getCode());
        sendData.setBizId(orderId);
        sendData.setDelayLevel(5);
        RocketProducerFactory.getProduct(MQTypeEnum.DELAY).send(sendData);
        return "success";
    }

    @PostMapping("/pay")
    public Object pay(Integer orderId) {
        sendOrderMsg(orderId, OrderOperateEnum.PRINT_ORDER.getCode());
        sendOrderMsg(orderId, OrderOperateEnum.WAREHOUSE_OUT.getCode());
        sendOrderMsg(orderId, OrderOperateEnum.LOGISTICS_DELIVERY.getCode());
        return "success";
    }

    private void sendOrderMsg(Integer id, String body) {
        SendObjectDTO sendData = new SendObjectDTO();
        sendData.setBody(body);
        sendData.setBizId(id);
        sendData.setId(id);
        sendData.setBizType(BizTypeEnum.ORDER_PAYMENT_SUCCESSFUL.getCode());
        RocketProducerFactory.getProduct(MQTypeEnum.ORDER).send(sendData);
    }
}
